//
//  ViewController.m
//  realmDB
//
//  Created by 蜂巢网络科技 on 2017/9/13.
//  Copyright © 2017年 fengchao. All rights reserved.
//

#import "ViewController.h"
#import "RQBook.h"

@interface ViewController ()
{
    BOOL _isFirst;
    BOOL _isLoad;
}
@property (weak, nonatomic) IBOutlet UILabel *contentLabel;
@property (weak, nonatomic) IBOutlet UIImageView *iconView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSArray*paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString*documentsDirectory =[paths objectAtIndex:0];
    
    NSLog(@"%@",documentsDirectory);
    
    _isFirst = YES;
}

- (IBAction)add
{
    RLMRealm *r = [RLMRealm defaultRealm];
    
    if (_isLoad) return;
    
    if (_isFirst) {
        RQBook *book = [[RQBook alloc]init];
        book.identifer =  [[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]] integerValue];
        book.bookName = @"跃迁";
//        book.authoraaa = @"古典";
        book.imageStr = [NSString imageToBase64Str:[UIImage imageNamed:@"7.jpg"]];
//        book.createAt = @"2017-12";
//        book.deleteAt = @"2016-12";

        [r transactionWithBlock:^{
            
            [r addObject:book];
            
        }];
        _isFirst = NO;
    }else{
        
        RQBook *book = [[RQBook alloc]init];
        book.identifer =  [[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]] integerValue];
        book.bookName = @"好好学习";
//        book.authoraaa = @"史蒂夫";
        book.imageStr = [NSString imageToBase64Str:[UIImage imageNamed:@"1.jpg"]];
        
        [r transactionWithBlock:^{
            
            [r addObject:book];
            
        }];
        
        _isLoad = YES;
    }
    
    NSLog(@"添加");
}


- (IBAction)delete
{
    RLMRealm *r = [RLMRealm defaultRealm];
    
    RLMResults *results =  [RQBook objectsWhere:@"bookName == %@",@"好好学习"];
    if (results.count) {
        RQBook *bookBeFound = [results firstObject];
        [r transactionWithBlock:^{
            
            [r deleteObject:bookBeFound];
        }];
    }
}


- (IBAction)update
{
    RLMRealm *r = [RLMRealm defaultRealm];
    
    RLMResults *results =  [RQBook objectsWhere:@"bookName == %@",@"跃迁"];
    if (results.count) {
        RQBook *bookBeFound = [results firstObject];
        [r transactionWithBlock:^{
            bookBeFound.bookName = @"精进";
//            bookBeFound.authoraaa = @"采铜";
            bookBeFound.imageStr = [NSString imageToBase64Str:[UIImage imageNamed:@"6.jpg"]];
        }];
    }
}


- (IBAction)query
{
    RLMResults *results =  [RQBook allObjects];
    
    for (RQBook *book in results) {
        NSLog(@"results : %@", book.bookName);
        
//        NSLog(@"%@",book.createAt);
//        NSLog(@"%@",book.deleteAt);

        
    }
    
}

@end
